module Observer
  def notifyobservers(var,oldvalue,newvalue)
    if(@observers==nil)
      return
    end
    if(@observers[var]==nil)
      return
    end
    @observers[var].each do |block|
      block.call(oldvalue,newvalue)
    end
  end
  def observe(var,&block)
    @observers ||= {}
    @observers[var] ||= []
    @observers[var] << block
    @observers.length
  end
  def unobserve(var,index)
    if(@observers==nil) return end
    if(@observers[var]==nil) return end
    @observers[var].delete_at index
  end

end
class Module
  def observable(*attrs)
    attrs.each do |attr|
      class_eval %{
	def #{attr}
	  @#{attr}
	end

	def #{attr}=(newvalue)
	  if(newvalue!=@#{attr})
	    notifyobservers :#{attr},@#{attr},newvalue
	  end
	  @#{attr}=newvalue
	end
      }
    end
    nil
  end  
end
